package com.ylbh.common.utils.ueditor.upload;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ylbh.common.utils.DateHelper;
import com.ylbh.common.utils.OSSClient;
import com.ylbh.common.utils.OSSClientUtil;
import com.ylbh.common.utils.ueditor.PathFormat;
import com.ylbh.common.utils.ueditor.define.AppInfo;
import com.ylbh.common.utils.ueditor.define.BaseState;
import com.ylbh.common.utils.ueditor.define.FileType;
import com.ylbh.common.utils.ueditor.define.State;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;




public class BinaryUploader {
    static Logger logger = LoggerFactory.getLogger(BinaryUploader.class);

    @Value("${url.uploadGoodsImg}")
	private static String uploadGoodsImg;

	public static final State save(HttpServletRequest request, Map<String, Object> conf) {

		boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;

		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}

		ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

        if ( isAjaxUpload ) {
            upload.setHeaderEncoding( "UTF-8" );
        }

		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multipartRequest.getFile("upfile");

			String savePath = (String) conf.get("savePath");
			String localSavePathPrefix = (String) conf.get("localSavePathPrefix");
			String originFileName = file.getOriginalFilename();
			String suffix = FileType.getSuffixByFilename(originFileName);

			originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
			savePath = savePath + suffix;

			long maxSize = ((Long) conf.get("maxSize")).longValue();

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}
			savePath = PathFormat.parse(savePath, originFileName);
			localSavePathPrefix = localSavePathPrefix + savePath;
			String physicalPath = localSavePathPrefix;
			logger.info("BinaryUploader physicalPath:{},savePath:{}",localSavePathPrefix,savePath);
//			InputStream is = file.getInputStream();

			//在此处调用ftp的上传图片的方法将图片上传到文件服务器
			String path = physicalPath.substring(0, physicalPath.lastIndexOf("/"));
			String picName = physicalPath.substring(physicalPath.lastIndexOf("/")+1, physicalPath.length());
//			State storageState = StorageManager.saveFileByInputStream(request, is, path, picName, maxSize);
//			State storageState = StorageManager.saveBinaryFile(file.getBytes(), path);
//			State storageState = uploadOSS(is, file, savePath);
			State storageState = uploadOSS(file);
//			is.close();

			if (storageState.isSuccess()) {
				//storageState.putInfo("url", storageState);
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}

			return storageState;
		} catch (Exception e) {
			return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		}
	}

//	public static State uploadOSS(InputStream is, MultipartFile file, String path){
//		State state = new BaseState();
//		state.putInfo( "size", file.getSize());
//		state.putInfo( "title", file.getName() );
//		OSSClient ossClient = new OSSClient();
//		state.putInfo("url", ossClient.uploadImg2Oss(file,"consumer/upload/store/","33307"+ DateHelper.getDate()));
//		return state;
//	}

	public static State uploadOSS(MultipartFile file){
		State state = new BaseState();
		state.putInfo( "size", file.getSize());
		state.putInfo( "title", file.getName() );
		String s = file.getContentType();
		if ("image/jpg".equals(file.getContentType()) || "image/jpeg".equals(file.getContentType()) || "image/png".equals(file.getContentType()) || "image/gif".equals(file.getContentType())) {
			OSSClient ossClient = new OSSClient();
			state.putInfo("url",  "http://image.yilianbaihui.cn/consumer/upload/store/" + "33307/"+ DateHelper.getDate() + "/" + ossClient.uploadImg2Oss(file,"consumer/upload/store/","33307/"+ DateHelper.getDate()));
		}
		if ("video/mp4".equals(file.getContentType()) || "video/avi".equals(file.getContentType()) || "video/gif".equals(file.getContentType())) {
			OSSClientUtil ossClient = new OSSClientUtil();
			state.putInfo("url",  "http://image.yilianbaihui.cn/consumer/video/1002/" + ossClient.uploadVideo(file,"video/1002"));
		}
		return state;
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
